package com.cjb.cloudsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cjb.cloudsecurity.JWT.TokenStoreCache;
import com.cjb.cloudsecurity.userMsg.entity.UserDetail;
import com.cjb.cloudsystem.entity.SysUser;
import com.cjb.cloudsystem.mapper.SysUserMapper;
import com.cjb.cloudsystem.service.SysUserService;
import com.cjb.cloudsystem.vo.EditPassword;
import com.cjb.cloudsystem.vo.SysUserVO;
import com.cjb.common.exception.ServerException;
import com.cjb.common.mybatisUtil.impl.BaseRepositoryImpl;
import com.cjb.common.query.DelEnum;
import com.cjb.common.security.TokenUtils;
import com.cjb.common.util.Common;
import com.cjb.common.util.HttpContextUtils;
import com.cjb.common.util.JsonUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author chenjinbin
 * @Package IntelliJ IDEA
 * @Class SysUsersServiceImpl
 * @Date 2023-07-27 21:41
 */
@Service
public class SysUserRepositoryImpl extends BaseRepositoryImpl<SysUserMapper, SysUser> implements SysUserService {
    /**
     * 日志
     */
    private final static Logger log = LoggerFactory.getLogger(SysUserRepositoryImpl.class);
    /**
     * token操作
     */
    @Autowired
    private TokenStoreCache tokenStoreCache;
    /*
     * 注入mapper层
     */
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 基础文件路径
     */
//    @Value("${basicPicDir}")
//    private String basicPicDir;
    /**
     * 单体保存
     *
     * @Author chenjinbin
     * @Value
     * @Title
     */
    @Override
    public boolean save(SysUser sysUser) {
        if (Common.isNull(sysUser.getId())){
            sysUser.setDeleted(0);
        }
        if (sysUser.getId() == null) {
            // 新增操作
            baseMapper.insert(sysUser);
        } else {
            // 修改操作
            baseMapper.updateById(sysUser);
        }
        return true;
    }

    /**
     * 批量保存
     *
     * @Author chenjinbin
     * @Value
     * @Title
     */
    @Override
    public Integer listSave(List<SysUser> sysUser) {
        return sysUserMapper.insertBatchSomeColumn(sysUser);
    }

    /**
     * 批量更新
     *
     * @Author chenjinbin
     * @Value
     * @Title
     */
    @Override
    public void listUpdate(List<SysUser> sysUser) {
        sysUserMapper.insertBatchSomeColumn(sysUser);
    }

    /**
     * 批量删除
     *
     * @Author chenjinbin
     * @Value
     * @Title
     */
    @Override
    public void listDelete(List<SysUser> sysUser) {
        if (Common.isNotEmpty(sysUser)) {
            List<Long> collect = sysUser.stream().map(SysUser::getId).distinct().collect(Collectors.toList());
            log.info("打印collect {}", JsonUtils.toJsonString(collect));
            sysUserMapper.deleteBatchIds(collect);
        }
    }

    /**
     * 通过id删除
     *
     * @Author chenjinbin
     * @Value
     * @Title
     */
    @Override
    public int deleteById(SysUser sysUser) {
        UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",sysUser.getId())
                .set("deleted",1);
        return sysUserMapper.update(sysUser,updateWrapper);
    }

    /**
     * 单个查询
     *
     * @Author chenjinbin
     * @Value
     * @Title
     */
    @Override
    public SysUser queryById(Long id) {
        return sysUserMapper.selectById(id);
    }

    /**
     * 分页
     *
     * @Author chenjinbin
     * @Value
     * @Title
     */
    @Override
    public Page queryPage(Page sysUserPage, SysUserVO sysUser) {
        return sysUserMapper.selectPage(sysUserPage, getWrapper(sysUser));
    }

    /**
     * 不分页查询
     *
     * @Author chenjinbin
     * @Value
     * @Title
     */
    private List<SysUser> queryList(SysUserVO sysUser) {
        return sysUserMapper.selectList(getWrapper(sysUser));
    }

    /**
     * 查询属性
     *
     * @Author chenjinbin
     * @Value
     * @Title
     */
    private LambdaQueryWrapper<SysUser> getWrapper(SysUserVO query) {
        LambdaQueryWrapper<SysUser> wrapper = Wrappers.lambdaQuery();
        if (Common.isNotNull(query.getId())) {
            wrapper.eq(SysUser::getId, query.getId());
        }
        if (Common.isNotNull(query.getUsername())) {
            log.info("打印username : {}", query.getUsername());
            wrapper.eq(SysUser::getUsername, query.getUsername());
        }
        if (Common.isNotNull(query.getPassword())) {
            wrapper.eq(SysUser::getPassword, query.getPassword());
        }
        if (Common.isNotNull(query.getRealName())) {
            wrapper.eq(SysUser::getRealName, query.getRealName());
        }
        if (Common.isNotNull(query.getAvatar())) {
            wrapper.eq(SysUser::getAvatar, query.getAvatar());
        }
        if (Common.isNotNull(query.getGender())) {
            wrapper.eq(SysUser::getGender, query.getGender());
        }
        if (Common.isNotNull(query.getEmail())) {
            wrapper.eq(SysUser::getEmail, query.getEmail());
        }
        if (Common.isNotNull(query.getMobile())) {
            wrapper.eq(SysUser::getMobile, query.getMobile());
        }
        if (Common.isNotNull(query.getOrgId())) {
            wrapper.eq(SysUser::getOrgId, query.getOrgId());
        }
        if (Common.isNotNull(query.getSuperAdmin())) {
            wrapper.eq(SysUser::getSuperAdmin, query.getSuperAdmin());
        }
        if (Common.isNotNull(query.getStatus())) {
            wrapper.eq(SysUser::getStatus, query.getStatus());
        }
        if (Common.isNotNull(query.getTenantId())) {
            wrapper.eq(SysUser::getTenantId, query.getTenantId());
        }
        if (Common.isNotNull(query.getVersion())) {
            wrapper.eq(SysUser::getVersion, query.getVersion());
        }
        wrapper.eq(SysUser::getDeleted, DelEnum.NO_DEL.getCode());

        if (Common.isNotNull(query.getCreator())) {
            wrapper.eq(SysUser::getCreator, query.getCreator());
        }
        if (Common.isNotNull(query.getCreateTime())) {
            wrapper.eq(SysUser::getCreateTime, query.getCreateTime());
        }
        if (Common.isNotNull(query.getUpdater())) {
            wrapper.eq(SysUser::getUpdater, query.getUpdater());
        }
        if (Common.isNotNull(query.getUpdateTime())) {
            wrapper.eq(SysUser::getUpdateTime, query.getUpdateTime());
        }
        wrapper.orderByDesc(SysUser::getId);
        return wrapper;
    }


    /**
     * 返回全部信息
     *
     * @Author chenjinbin
     * @Value
     * @Title
     */
    @Override
    public List<SysUser> returnAllData() {
        return sysUserMapper.selectList(null);
    }

    /**
     * 获取用户信息
     *
     * @Author chenjinbin
     * @Value
     * @Title
     */
    @Override
    public UserDetail getUser() {
        UserDetail user;
        try {
            user = (UserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (Exception e) {
            return null;
        }

        return user;
    }

    /**
     * 密码修改
     *
     * @Author chenjinbin
     * @Value
     * @Title
     */
    @Override
    public UserDetail editPassword(EditPassword editPassword) {
        log.info("打印收到的内容 {}", JsonUtils.toJsonString(editPassword));
        if (Common.isNotEmptyVales(editPassword.getPassword(), editPassword.getNewPassword(), editPassword.getConfirmPassword())) {
            if (editPassword.getPassword().equals(editPassword.getNewPassword())) {
                throw new ServerException("新密码与旧密码一致");
            }
            if (!editPassword.getNewPassword().equals(editPassword.getConfirmPassword())) {
                throw new ServerException("验证密码与新密码不一致");
            }
        }

        /*认证原密码*/
        if (Common.isNotEmpty(editPassword.getUsername())) {
            SysUserVO sysUserVO = new SysUserVO();
            sysUserVO.setUsername(editPassword.getUsername());
            sysUserVO.setPassword(editPassword.getPassword());
            List<SysUser> sysUsers = queryList(sysUserVO);
            if (Common.isNotEmpty(sysUsers) && sysUsers.size() > 0) {
                SysUser sysUser = sysUsers.get(0);
                sysUser.setPassword(editPassword.getNewPassword());
                save(sysUser);
            }
        }
        /*修改密码*/
        return null;
    }

    /**
     * 更换头像
     *
     * @Author chenjinbin
     * @Value
     * @Title
     */
    @Override
    public void upload(MultipartFile file, String dir){
//        if (Common.isEmpty(file)){
//            new ServerException("文件上传是空的");
//        }
//        if (Common.isEmpty(dir)){
//            dir = file.getOriginalFilename();
//        }
//        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
//        UserDetail user = tokenStoreCache.getUser(TokenUtils.getAccessToken(request));
//        log.info("token中获取的数据 {}",JsonUtils.toJsonString(user));
//        SysUser sysUser = new SysUser();
//        try {
//            Common.copyNonNullProperties(user,sysUser);
//        } catch (Throwable e) {
//            log.info("复制异常");
//        }
//        log.info("待入库的文件 {}",JsonUtils.toJsonString(user));
//        try {
//            hadoopUtil.uploadFile(file.getBytes(),dir);
//            log.info("打印上传的路径 {}",dir);
//            //文件入库
//            if (Common.isNotEmpty(sysUser)){
//                dir= basicPicDir+dir;
//                sysUser.setAvatar(dir);
//                this.updateById(sysUser);
//            }
//
//        } catch (Exception e) {
//            throw new ServerException("文件上传发生异常"+e.getMessage());
//        }
//
//        //文件入库
//        log.info("这边是文件入库xxxx");
    }


}